<template>
  <div class="file-input">
    <input type="file" ref="file_upload" :accept="accept" name="file" />
    <div class="file-btn" v-show="!isFile" style="text-align: center">选择文件</div>
    <div class="file-btn" v-show="isFile">已选文件:{{ uploadFile }}</div>
  </div>
</template>
<script>
  export default {
    name: "FileUpload",
    props: {
      accept: {
        type: String,
        default: "*",
      },
      isCheck: {
        type: Boolean,
        default: false,
      },
    },
    data: () => ({
      isFile: false,
      uploadFile: "",
    }),
    methods: {},
    mounted() {
      var that = this;
      this.$refs.file_upload.onchange = function () {
        var val = this.value;
        var file = val.substring(val.lastIndexOf("\\") + 1, val.length);
        if (file) {
          that.isFile = true;
          that.uploadFile = file;
          if (that.isCheck) {
            if (this.files[0].size > 1024 * 1024) {
              that.app.$emit("show-alert-msg", that.$t("systemDevice.fileOverSize"));
            } else {
              that.$emit("select-file", this.files);
            }
          } else {
            that.$emit("select-file", this.files);
          }
        } else {
          that.isFile = false;
        }
      };
      this.files = "";
      this.uploadFile = "";
    },
  };
</script>

<style lang="scss" scoped>
  //自定义文件上传按钮 start
  .file-input {
    display: inline-block;
    width: 250px;
    // padding: 0 8px;
    height: 30px;
    overflow: hidden;
    color: #606266;

    input[type="file"] {
      position: relative;
      z-index: 2;
      opacity: 0;
      width: 250px;
      height: 30px;
      background: transparent;
      color: transparent;
    }

    .file-btn {
      color: #606266;
      position: relative;
      z-index: 1;
      top: -30px;
      width: 250px;
      text-align: left;
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 30px;
      color: #ffffff;
      background-color: #1baeae;
      border-color: #1baeae;
      white-space: nowrap;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      border-radius: 3px;
      font-size: 14px;
      padding: 0 10px;
    }
  }

  .file-input.active {
    background-image: linear-gradient(#ffffff, #bee1f1);
  }
</style>
